package com.example.group.network.express_plus_app.ui.mine;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;


import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.example.group.network.express_plus_app.MyOrderHistoryActivity;
import com.example.group.network.express_plus_app.MyPostActivity;
import com.example.group.network.express_plus_app.MyReceiveOrderHistoryActivity;
import com.example.group.network.express_plus_app.MyReceiveOrdersActivity;
import com.example.group.network.express_plus_app.R;
import com.example.group.network.express_plus_app.SettingsActivity;
import com.example.group.network.express_plus_app.WaitFinishActivity;
import com.example.group.network.express_plus_app.data.model.LoggedInUser;
import com.example.group.network.express_plus_app.http.MySingleton;
import com.example.group.network.express_plus_app.ui.login.LoginActivity;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MineFragment extends Fragment implements View.OnClickListener {
    RequestQueue queue;
    TextView tv_net_name;
    private MineViewModel mineViewModel;
    @BindView(R.id.iv_face)
    ImageView iv_volley;
    private ImageLoader imageLoader;
    Toolbar toolbar;
    private String imagePath;
    @BindView(R.id.ly_my_post)
    LinearLayout ly_my_post;
    @BindView(R.id.ly_wait_finish)
    LinearLayout ly_wait_finish;
    @BindView(R.id.ly_my_receive_order)
    LinearLayout ly_my_receive_order;
    @BindView(R.id.ll_order_history)
    LinearLayout ll_order_history;
    @BindView(R.id.ll_receive_order_history)
    LinearLayout ll_receive_order_history;
    @BindView(R.id.tv_user_phone)
    TextView tv_user_phone;
    @BindView(R.id.textView8)
    TextView textView8;



    @SuppressLint("RestrictedApi")
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_mine, container, false);

        ButterKnife.bind(this,root);//注意位置 否则报错
        queue= MySingleton.getInstance(getContext()).
                getRequestQueue();
        imageLoader=MySingleton.getInstance(getContext()).getImageLoader();
        tv_net_name = root.findViewById(R.id.tv_net_name);
        toolbar=root.findViewById(R.id.toolbar_mine);
        toolbar.setTitle("我的");
        toolbar.inflateMenu(R.menu.menu_overflow);

        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (item.getItemId()==R.id.menu_setting){
                    Intent intent = new Intent(getActivity(), SettingsActivity.class);
                    startActivity(intent);
                }
                return true;
            }
        });

        mineViewModel =
                new ViewModelProvider(this,new MineViewModelFactory(getContext())).get(MineViewModel.class);
        mineViewModel.getUserFromSQ();
        mineViewModel.getUser().observe(getViewLifecycleOwner(), new Observer<LoggedInUser>() {
            @Override
            public void onChanged(LoggedInUser loggedInUser) {
                if (loggedInUser == null) {
                    Intent intent=new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                }else {
                    tv_net_name.setText(loggedInUser.getDisplayName());
                    tv_user_phone.setVisibility(View.VISIBLE);
                    textView8.setVisibility(View.VISIBLE);
                    tv_user_phone.setText(loggedInUser.getPhone());
                    imagePath = loggedInUser.getImagePath();
                    ImageLoaderByURL();
                }
            }
        });
        ly_my_post.setOnClickListener(this);
        ly_wait_finish.setOnClickListener(this);
        ly_my_receive_order.setOnClickListener(this);
        ll_order_history.setOnClickListener(this);
        ll_receive_order_history.setOnClickListener(this);
        return root;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    //oncreate是最先加载的页面onCreate->onStart->onResume
    //没用的方法
    @Override
    public void onStart() {
        mineViewModel.getUser().observe(getViewLifecycleOwner(), new Observer<LoggedInUser>() {
            @Override
            public void onChanged(LoggedInUser loggedInUser) {
                if (loggedInUser == null) {
                    Intent intent=new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                }else {
                    tv_net_name.setText(loggedInUser.getDisplayName());

                }
            }
        });
        super.onStart();
    }
    /**
     * 吃出使用ImageLoader,ImageLoader比ImageRequest更高效，功能功能更多
     */
    public void ImageLoaderByURL(){
        String server_ip=getActivity().getString(R.string.server_ip);
        String url=server_ip+"express-user/images/"+imagePath;
        ImageLoader.ImageListener listener= ImageLoader.getImageListener(iv_volley,R.mipmap.ic_launcher,R.mipmap.ic_launcher);
        imageLoader.get(url,listener);//后边也可以添加参数，进行图片压缩，设置填充格式
    }

    //获取发布版sHA1码
    public static String sHA1(Context context){
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            return result.substring(0, result.length()-1);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id==R.id.ly_my_post){
            Intent intent = new Intent(getActivity(), MyPostActivity.class);
            startActivity(intent);
        }else if (id==R.id.ly_wait_finish){
            Intent intent = new Intent(getActivity(), WaitFinishActivity.class);
            startActivity(intent);
        }else if (id==R.id.ly_my_receive_order){
            Intent intent = new Intent(getActivity(), MyReceiveOrdersActivity.class);
            startActivity(intent);
        }else if (id==R.id.ll_order_history){
            Intent intent = new Intent(getActivity(), MyOrderHistoryActivity.class);
            startActivity(intent);
        }else if (id==R.id.ll_receive_order_history){
            Intent intent = new Intent(getActivity(), MyReceiveOrderHistoryActivity.class);
            startActivity(intent);
        }
    }
}